/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controller;

import java.io.IOException;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspWriter;
import model.Employee;
import model.Employeeproject;
import model.Position;
import session.EmployeeFacadeRemote;
import session.PositionFacadeRemote;
import session.EmployeeprojectFacadeRemote;
import session.ProjectFacadeRemote;
import util.Constants;

/**
 *
 * @author TIT
 */
public class employeeController {
    public static EmployeeFacadeRemote getEmployeeFacade() throws NamingException {
        return util.Facade.getEmployeeFacade();
    }
    
    public static PositionFacadeRemote getPositionFacade() throws NamingException {
            return util.Facade.getPositionFacade();
        }
    public static ProjectFacadeRemote getProjectFacade() throws NamingException{
        return util.Facade.getProjectFacade();
    } 
    public static EmployeeprojectFacadeRemote getEmployeeProjectFacade() throws NamingException{
        return util.Facade.getEmployeeProjectFacade(); 
   }

    public static String getActionLink(int id) {
        String edit = "<a onclick=\"doAction(frmIndex, '" + Constants.ADMIN_PAGE_NAME +
                "', '" + Constants.USER_MANAGEMENT_PAGE_NAME + "', '" + Constants.USER_EDIT +
                "', '" + Constants.SHOW_EDIT_PAGE +"', '" + id + "')\">Edit</a>";
        String delete = "<a onclick=\"doAction(frmIndex, '" + Constants.ADMIN_PAGE_NAME +
                "', '" + Constants.USER_MANAGEMENT_PAGE_NAME + "', '" + Constants.USER_LIST+
                "', '" + Constants.DELETE +"', '" + id + "')\">Delete</a>";
        String show_more = "<a onclick=\"doAction(frmIndex, '" + Constants.ADMIN_PAGE_NAME +
                "', '" + Constants.USER_MANAGEMENT_PAGE_NAME + "', '" + Constants.USER_DETAIL+
                "', '" + Constants.SHOW_MORE +"', '" + id + "')\">Show_more</a>";
        return edit + delete + show_more;
    }
    
    public static String getActionEmployeeLink(String id, String Status) {
        
        String join     = "Join";
        String leave    = "Leave";        
        if(Status.equalsIgnoreCase("-") //is not join, join accessable
            || Status.equalsIgnoreCase("0")){//is not working, join accessable
            join = "<a onclick=\"doAction(frmIndex, '" + Constants.ADMIN_PAGE_NAME +
                "', '" + Constants.USER_MANAGEMENT_PAGE_NAME + "', '" + Constants.USER_DETAIL +
                "', '" + Constants.JOIN +"', '" + id + "')\">Join</a>";
        }else if(Status.equalsIgnoreCase("1")){//is working, leave accessable
            leave = "<a onclick=\"doAction(frmIndex, '" + Constants.ADMIN_PAGE_NAME +
                "', '" + Constants.USER_MANAGEMENT_PAGE_NAME + "', '" + Constants.USER_DETAIL+
                "', '" + Constants.LEAVE +"', '" + id + "')\">Leave</a>";
        }        
        return join + leave;
    }
    
    public static int id() throws NamingException{
        int employid = 0;
        List<model.Employee> employeesList = getEmployeeFacade().findAll();
         for(int i = 0; i < employeesList.size(); i++) {
                Employee node = employeesList.get(i);
                if(node.getEmployeeID() > employid || node.getEmployeeID() == employid){
                    employid = node.getEmployeeID();
                }
         }
         return employid +1;
    }
    
    public static void showAllEmployee(JspWriter out) {
        Controller.log.info("showAllUser");
        
        try {
            List<model.Employee> employeesList = getEmployeeFacade().findAll();

            //Create the title
            out.println("<div id='list-table'>");
            out.println("<div class='row'>");
            out.println("<div class='column-header' style='width: " +
                    Constants.ID_COLUMN_SIZE +";'>ID</div>");
            out.println("<div class='column-header' style='width: " +
                    Constants.OBJECT_NAME_COLUMN_SIZE +";'>Name</div>");
            out.println("<div class='column-header' style='width: " +
                    Constants.OBJECT_NAME_COLUMN_SIZE +";'>ShortName</div>");
            out.println("<div class='column-header' style='width: " +
                    Constants.OBJECT_NAME_COLUMN_SIZE +";'>Gender</div>");
             out.println("<div class='column-header' style='width: " +
                    Constants.OBJECT_NAME_COLUMN_SIZE +";'>Bỉrth</div>");
             out.println("<div class='column-header' style='width: " +
                    Constants.OBJECT_NAME_COLUMN_SIZE +";'>PersonalID</div>");
             out.println("<div class='column-header' style='width: " +
                    Constants.OBJECT_NAME_COLUMN_SIZE +";'>Position</div>");
            out.println("<div class='column-header' style='width: " +
                    Constants.OBJECT_NAME_COLUMN_SIZE +";'>Action</div>");
            out.println("<div class='clear'></div>");
            out.println("</div>");

            //Show Values
            for(int i = 0; i < employeesList.size(); i++) {
                String gtt;
                Employee node = employeesList.get(i);
                Position position = node.getPositionID();
                int year = node.getBirth().getYear()+1900;
                int month = node.getBirth().getMonth();
                if(node.getGender() == true){
                    gtt = "Male";
                }else{
                    gtt = "Female";
                }
                out.println("<div class='row'>");
                out.println("<div class='column' style='width: " +
                        Constants.ID_COLUMN_SIZE +";'>" +
                        node.getEmployeeID() + "</div>");
                out.println("<div class='column' style='width: " +
                        Constants.OBJECT_NAME_COLUMN_SIZE +";'>" +
                        node.getName() + "</div>");
                out.println("<div class='column' style='width: " +
                        Constants.OBJECT_NAME_COLUMN_SIZE +";'>" +
                        node.getShortName() + "</div>");
                out.println("<div class='column' style='width: " +
                        Constants.OBJECT_NAME_COLUMN_SIZE +";'>" +
                        gtt + "</div>");
                out.println("<div class='column' style='width: " +
                        Constants.OBJECT_NAME_COLUMN_SIZE +";'>" +
                        node.getBirth().getDate()+"/"+month+"/"+year+"</div>");
                out.println("<div class='column' style='width: " +
                        Constants.OBJECT_NAME_COLUMN_SIZE +";'>" +
                        node.getPersonalID() + "</div>");
                out.println("<div class='column' style='width: " +
                        Constants.OBJECT_NAME_COLUMN_SIZE +";'>" +
                        position.getName() + "</div>");
                out.println("<div class='column' style='width: " +
                        Constants.ACTION_COLUMN_SIZE +";'>" +
                    getActionLink(node.getEmployeeID()) +"</div>");
                out.println("</div>");
                out.println("<div class='clear'></div>");
            }
            out.println("</div>");
            Controller.log.info("showAllEmployee finish.");
        } catch(Exception ex) {
            Controller.log.error("Error showAllEmployee: " + ex.getMessage());
        }
    }
    
    public static void showEmployeeName(JspWriter out, String employeeID) {
        try {
            Employee em = getEmployeeFacade().find(employeeID);
            out.println("<div id = 'info'>");
            out.println("123");
            out.println("<div class='clear'></div>");
            out.println("</div>");
        } catch (Exception ex) {
            Controller.log.error("Error showEmployeeName: " + employeeID);
        }
        
    }
    public static void showEmployeeStatus(JspWriter out, HttpServletRequest request){
        try{            
            String employeeId = request.getParameter("employeeId");
            List<model.Project> projectList = getProjectFacade().findAll();
            //Show all project list on screen
            //create title
            out.println("<div id='list-table'>");
            out.println("<div class='row'>");
            out.println("<div class='column-header' style='width: " +
                    Constants.OBJECT_NAME_COLUMN_SIZE +";'>Project</div>");//project name
            out.println("<div class='column-header' style='width: " +
                    Constants.OBJECT_DESCRIPTION_COLUMN_SIZE +";'>Description</div>");//project decrib
            out.println("<div class='column-header' style='width: " +
                    Constants.DATE_COLUMN_SIZE +";'>Joined Day</div>");//joined day
            out.println("<div class='column-header' style='width: " +
                    Constants.OBJECT_NAME_COLUMN_SIZE +";'>Status</div>");//status working  or out  
            out.println("<div class='column-header' style='width: " +
                    Constants.OBJECT_NAME_COLUMN_SIZE +";'>Posittion</div>");  //postion of employee in project    
            out.println("<div class='column-header' style='width: " +
                    Constants.ACTION_COLUMN_SIZE +";'>Action</div>");//action Join/Quit
            out.println("<div class='clear'></div>");
            out.println("</div>");

            //show value
            String position = "-";
            String join_day = "-";
            String Status = "-";
            model.Employee employee = getEmployeeFacade().find(employeeId);            
            for(int i = 0; i < projectList.size(); i++) {
                model.Project node = projectList.get(i);
                //find all employee in this project
                List<model.Employeeproject> employeeProject = getEmployeeProjectFacade().findListEmployeeByProjectID(node.getProjectID());
                for(int j = 0; j < employeeProject.size(); j++)
                {
                    model.Employeeproject node1 = employeeProject.get(j);
                    if(node1.getEmployee().getPersonalID().equalsIgnoreCase(employeeId)){
                        position = employee.getPositionID().getPositionID();
                        join_day = node1.getJoinedDate().toString();
                        if(node1.getStatus()==1){
                            Status = "Working";
                        }else{
                            Status = "Stopped";
                        }
                    }
                    out.println("<div class='row'>");
                    out.println("<div class='column' style='width: " +
                            Constants.OBJECT_NAME_COLUMN_SIZE +";'>" +
                            node.getName() + "</div>");
                    out.println("<div class='column' style='width: " +
                            Constants.OBJECT_DESCRIPTION_COLUMN_SIZE +";'>" +
                            node.getDescription() +"</div>");
                    out.println("<div class='column' style='width: " +
                            Constants.DATE_COLUMN_SIZE +";'>" +
                            join_day+"</div>");
                    out.println("<div class='column' style='width: " +
                            Constants.OBJECT_NAME_COLUMN_SIZE +";'>" +
                            Status +"</div>");
                    out.println("<div class='column' style='width: " +
                            Constants.OBJECT_NAME_COLUMN_SIZE +";'>" +
                            position +"</div>");
                    out.println("<div class='column' style='width: " +
                            Constants.ACTION_COLUMN_SIZE +";'>" +
                            getActionEmployeeLink(node.getProjectID(),Status) +"</div>");
                    out.println("</div>");
                    out.println("<div class='clear'></div>");
                }
            }
       } catch(Exception ex) {
            Controller.log.error("Error showEmployeeStatus: " + ex.getMessage());
           }
    }
    
    public static void addDataPosition(JspWriter out) {
        Controller.log.info("add Data Position");
        try {
            /*
             * Create Session Bean to do bussiness method
             */
            Context context = new InitialContext();
            Object ref = context.lookup("java:global/ejb-serv/PositionFacade");
            PositionFacadeRemote sevBean = (PositionFacadeRemote) ref;
            /*
             * Show position List on Screen
             */
            List<model.Position> listLog = sevBean.findAll();
            for (int i = 0; i < listLog.size(); i++) {
                Position a = listLog.get(i);
//                if(i==2)
//                    out.println("<option value='" + a.getPositionID() + "' selected='selected'>" + a.getName() + "</option>");
//                else
                    out.println("<option value='" + a.getPositionID() + "'>" + a.getName() + "</option>");
            }
            Controller.log.info("show position finish.");
        } catch (Exception ex) {
            Controller.log.error("Error show posiotionl list : " + ex.getMessage());
        }
    }
    
    public static Date birth(String date, String month, String year){
        Date birth;
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.DATE, Integer.parseInt(date));
        calendar.set(Calendar.MONTH, Integer.parseInt(month));
        calendar.set(Calendar.YEAR, Integer.parseInt(year));
        birth=calendar.getTime();   
        return birth;    
    }
    
    public static Boolean gd(String gt){
        if("Female".equals(gt)){
            return false;
        }else      
            return true;
    }
    
    public static void processAction(HttpServletRequest request)  throws Exception{
        String action = request.getParameter("action");
        Controller.log.info(request.getParameter("selectedItemID"));
        Controller.log.info("createEditController.processAction");

        try {
            if (Constants.INSERT.equalsIgnoreCase(action)) {
                Controller.log.info("Insert Defectlog: ");
                //Process INSERT action.
               
                Controller.log.info("Date: " + request.getParameter("date") + "; Month: " + request.getParameter("month") + "; Year: " + request.getParameter("year"));
                Date birth = birth(request.getParameter("date"), request.getParameter("month"), request.getParameter("year"));
                Controller.log.info("Birth: " + birth.toString());
                //java.sql.Date a = new java.sql.Date(birth.getTime());
                //Controller.log.info("a: " + a.toString());
                String name = request.getParameter("name");
                
                String shortname = request.getParameter("shortname");
                
                PositionFacadeRemote positionFacade = getPositionFacade();
                Position position = positionFacade.find(request.getParameter("position"));
                position = positionFacade.merge(position);
                
               // int employid = Integer.parseInt(request.getParameter("employid"));
                int employid = id();
                String personalid = request.getParameter("personalid");
                String password = request.getParameter("password");
                String gender = request.getParameter("gender");
                
                
                name = util.Unicode.changeToUnicode(name);
                shortname = util.Unicode.changeToUnicode(shortname);
                
                if ((name == null) || "".equals(name)) {
                    //If the ID is null.
                    Controller.sendMessage(request, "Please input name.", true);
                    throw new Exception("The input Name is null.");
                } else if ((shortname == null) || "".equals(shortname)) {
                    //If the Name is null.
                    Controller.sendMessage(request, "Please input shortname.", true);
                    throw new Exception("The input shortname is null.");
                } else if( (gender == null)||"".equals(gender) ){
                
                    Controller.sendMessage(request, "Please input gender.", true);
                    throw new Exception("The input gender is null.");
                }else {
                    EmployeeFacadeRemote server = getEmployeeFacade();
                    Employee employee = new Employee();

                    employee.setEmployeeID(employid);
                    employee.setName(name);
                    employee.setBirth(birth);
                    employee.setShortName(shortname);
                    employee.setGender(gd(gender));
                    employee.setPersonalID(personalid);
                    employee.setPassword(password);
                    employee.setPositionID(position);
                    
                    server.insert(employee);

                    Controller.sendMessage(request, "Insert Successfully.", false);
                    Controller.log.info("Insert Employee End.");
                }
            }else if(Constants.SHOW_EDIT_PAGE.equalsIgnoreCase(action)) {
                //Process SHOW_EDIT_PAGE action.
                int selectedID = Integer.parseInt(request.getParameter("selectedItemID"));
                if((request.getParameter("selectedItemID") == null) || "".equals(request.getParameter("selectedItemID"))) {
                    //If the selectedID is null, throw an Exception.
                    throw new Exception("No selected id to edit.");
                } else {
                    //Get value to send back to Edit page.
                    Employee employee = getEmployeeFacade().find(selectedID);
                    if(employee == null) {
                        throw new Exception("The selected User not found.");
                    } else {
                        
                        String gt="Male";
                        if(employee.getGender() == false){
                            gt = "Female";
                        }
                        HttpSession session = request.getSession();
                        session.setAttribute("employid", Integer.toString(employee.getEmployeeID()));
                        session.setAttribute("name", employee.getName());
                        session.setAttribute("shortname", employee.getShortName());
                        session.setAttribute("date", Integer.toString(employee.getBirth().getDate()));
                        session.setAttribute("month", Integer.toString(employee.getBirth().getMonth()));
                        session.setAttribute("year", Integer.toString(employee.getBirth().getYear()+1900));
                        session.setAttribute("gender",gt);
                        session.setAttribute("personalid", employee.getPersonalID());
                        session.setAttribute("password", employee.getPassword());
                        session.setAttribute("positionid", employee.getPositionID());
                    }
                }

            }
            else if(Constants.DELETE.equalsIgnoreCase(action)) {
               
                int selectedID = Integer.parseInt(request.getParameter("selectedItemID"));
                getEmployeeFacade().deleteByID(selectedID);
                Controller.sendMessage(request, "Deleted employee: " + selectedID, false);
                Controller.log.info("Deleted employee: " + selectedID);
            
            }else if(Constants.EDIT.equalsIgnoreCase(action)){
                
               //Controller.log.info("Date: " + request.getParameter("date") + "; Month: " + request.getParameter("month") + "; Year: " + request.getParameter("year"));
            
               Date birth = birth(request.getParameter("date"), request.getParameter("month"), request.getParameter("year"));
                                    Controller.log.info(birth.getTime());
                java.sql.Date a = new java.sql.Date(birth.getTime());
                String name = request.getParameter("name");
                                    Controller.log.info(name);
                String shortname = request.getParameter("shortname");         
                                   Controller.log.info(shortname);
                PositionFacadeRemote positionFacade = getPositionFacade();
                Position position = positionFacade.find(request.getParameter("position"));
                
                position = positionFacade.merge(position);
                                   Controller.log.info(position);
                                   Controller.log.info(request.getParameter("employid"));             
                int employid = Integer.parseInt(request.getParameter("employid"));
                String personalid = request.getParameter("personalid");
                String password = request.getParameter("password");
                                   Controller.log.info(password);
                String gender = request.getParameter("gender");
                                   Controller.log.info(gender);
                
                
                name = util.Unicode.changeToUnicode(name);
                shortname = util.Unicode.changeToUnicode(shortname);
                
                if((name == null) || "".equals(name)) {
                    //If the Name is null.
                    Controller.sendMessage(request, "Please input Name.", true);
                    throw new Exception("The input Name is null.");
                } else {
                    
                    EmployeeFacadeRemote server = getEmployeeFacade();
                    Employee employee = server.find(employid);
                    
                    if(employee == null) {
                        throw new Exception("Cannot found the target User.");
                    } else {
                        employee.setEmployeeID(employid);
                        employee.setName(name);
                        employee.setBirth(birth);
                        employee.setShortName(shortname);
                        employee.setGender(gd(gender));
                        employee.setPersonalID(personalid);
                        employee.setPassword(password);
                        employee.setPositionID(position);
                        
                        server.edit(employee);
                    }
                }
            }else if(Constants.SHOW_MORE.equalsIgnoreCase(action)){
                //process show more page
                int selectedID = Integer.parseInt(request.getParameter("selectedItemID"));
                if((request.getParameter("selectedItemID") == null) || "".equals(request.getParameter("selectedItemID"))) {
                    //If the selectedID is null, throw an Exception.
                    Controller.log.info("Employee not found " + selectedID);
                    throw new Exception("No selected id to edit.");                    
                } else {
                    //Get value to send back to show more page.
                    Employee employee = getEmployeeFacade().find(selectedID);
                    if(employee == null) {
                        throw new Exception("The selected User not found.");
                    }
                        HttpSession session = request.getSession();
                        session.setAttribute("employeeid", Integer.toString(employee.getEmployeeID()));
                    }  
            }else if(Constants.JOIN.equalsIgnoreCase(action)){
                //process join action
                int selectedID = Integer.parseInt(request.getParameter("selectedItemID"));
                if((request.getParameter("selectedItemID") == null) || "".equals(request.getParameter("selectedItemID"))) {
                    //If the selectedID is null, throw an Exception.
                    throw new Exception("No selected id to show.");
                } else {                    
                    model.Employeeproject employeeProject = new Employeeproject();
                    employeeProject.setEmployee(getEmployeeFacade().find(request.getParameter("employeeid")));                     
                    employeeProject.setJoinedDate(new Date());
                    employeeProject.setProject(getProjectFacade().find(selectedID));
                    employeeProject.setStatus(1);
                    
                }
            }else if(Constants.LEAVE.equalsIgnoreCase(action)){
                //process leave action
                int selectedID = Integer.parseInt(request.getParameter("selectedItemID"));
                if((request.getParameter("selectedItemID") == null) || "".equals(request.getParameter("selectedItemID"))) {
                    //If the selectedID is null, throw an Exception.
                    throw new Exception("No selected id to show.");
                } else {                    
                    model.Employeeproject employeeProject = new Employeeproject(); 
                    employeeProject = getEmployeeProjectFacade().find(request.getParameter("employeeid"));
                    employeeProject.setStatus(0);    
                }
            }
        } catch (Exception ex) {
           // Controller.log.info(request.getParameter("birth"));
            Controller.log.error("Error EmployeeController.processAction: " + ex.getMessage());
        }
    }
}
